﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;
using static Modules.Project.ProjectConstants;

namespace Modules.System.Dept
{
    [UseDI(ServiceLifetime.Scoped)]
    public class SysDeptRepository : Repository<SysDept, DefaultDbContext>
    {
        private readonly ILogger logger;

        public SysDeptRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, ILogger<SysDeptRepository> logger)
            : base(dbContext, applicationContext)
        {
            this.logger = logger;
        }

        public IPagedList<SysDept> GetDepts(DeptQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("dept_id")
                .From("sys_dept");
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(name Like @0 or code Like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (query.AreaId.HasValue)
                sql.Where(" (province_code=@0 or city_code=@0 or area_code=@0)", query.AreaId);
            if (query.Level.HasValue)
                sql.Where("level=@0", query.Level.Value);
            if (query.IndustryType.HasValue)
                sql.Where("industry_type=@0", (int)query.IndustryType.Value);
            sql.Where("is_deleted=0");
            sql.OrderBy("create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }

        public IEnumerable<SysDept> GetDeptsByIndustryType(行业主管部门 industryType)
        {
            int areaVersion = EntityCacheService.GetAreaVersion("IndustryType", industryType);
            return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
            {
                return $"DeptsByIndustryType:{industryType}:{areaVersion}";
            }, () =>
            {
                Sql sql = Sql.Builder
                .Select("dept_id")
                .From("sys_dept")
                .Where("industry_type=@0", industryType);
                sql.OrderBy("create_time DESC");
                return sql;
            });
        }
    }
}